package com.example.musicapp.view;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.widget.Toolbar;
import androidx.core.app.ActivityCompat;
import androidx.core.view.GravityCompat;
import androidx.drawerlayout.widget.DrawerLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;

import android.net.Uri;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;

import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;

import com.example.musicapp.R;
import com.example.musicapp.adapter.MusicAdapter;
import com.example.musicapp.application.MyApp;
import com.example.musicapp.base.BaseActivity;
import com.example.musicapp.bean.Music;
import com.example.musicapp.contract.IHomeContract;

import com.example.musicapp.utils.CommonUtils;
import com.google.android.material.navigation.NavigationView;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;


import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import static com.example.musicapp.application.MyApp.sJSessionId;


/**
 * @author tangan
 * 首页面
 */
public class HomeActivity extends BaseActivity<IHomeContract.HomePresenter> implements IHomeContract.HomeUi, View.OnClickListener {

    /**
     * 跳转到登录页面的码
     */
    public static final int HOME_TO_LOGIN_ACTIVITY_CODE = 1;
    private static final int TURN_TO_SEARCH = 2;
    private DrawerLayout mDrawerLayout;
    private NavigationView mNavView;
    private List<Music> mMusicList = new ArrayList<>();
    private MusicAdapter myAdapter;
    private TextView mTvUsername;
    private boolean mLoginFLag = false;
    private SharedPreferences mPreferences;

    @Override
    public IHomeContract.HomePresenter onBindPresenter() {
        return new com.example.musicapp.presenter.HomePresenter(this);
    }


    @Override
    protected void initData() {
        requestPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
        requestPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        autoLogin();
    }

    /**
     * 抽屉布局里
     */
    private void setCircleImagineListener() {
        View headerLayout = mNavView.inflateHeaderView(R.layout.nav_header);
        ImageView mHeadImage = headerLayout.findViewById(R.id.icon_image);
        mTvUsername = headerLayout.findViewById(R.id.tv_username);
        mHeadImage.setOnClickListener(this);

    }


    @Override
    protected void initView() {
        //扫描本地音乐
        mMusicList = CommonUtils.getAllMusic();

        SmartRefreshLayout smartRefreshLayout = findViewById(R.id.refreshLayout);
        //smartRefreshLayout.autoLoadMore();//自动加载
        //smartRefreshLayout.autoRefresh();//自动刷新
        smartRefreshLayout.setEnableAutoLoadMore(true);//是否启用列表惯性滑动到底部时自动加载更多
        smartRefreshLayout.setEnableLoadMore(true);//是否启用加载更多功能
        smartRefreshLayout.setEnableRefresh(true);//是否启用下拉刷新功能
        RecyclerView recyclerView = findViewById(R.id.rv_music);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        myAdapter = new MusicAdapter(mMusicList);
        myAdapter.setOnItemClickListener((view, position) -> {
            if (view.getId() == R.id.iv_manage) {
                addMenu(position, view);
            } else {
                playMusicAndTurn(position);
            }

        });
        recyclerView.setAdapter(myAdapter);
        smartRefreshLayout.setOnRefreshListener(refreshLayout -> {
            Toast.makeText(HomeActivity.this, "我请求下拉刷新数据", Toast.LENGTH_LONG).show();

            mMusicList = CommonUtils.getAllMusic();
            myAdapter.setList(mMusicList);
            myAdapter.notifyDataSetChanged();
            refreshLayout.finishRefresh();//下拉刷新结束
            //refreshLayout.finishRefresh(2000);//2s结束

        });
        smartRefreshLayout.setOnLoadMoreListener(refreshLayout -> {
            Toast.makeText(HomeActivity.this, "我请求加载更多数据", Toast.LENGTH_SHORT).show();
            myAdapter.notifyDataSetChanged();
            refreshLayout.finishLoadMore();
        });
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mNavView = (NavigationView) findViewById(R.id.nav_view);


        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
            actionBar.setHomeAsUpIndicator(R.drawable.ic_baseline_menu_24);
        }


//        mNavView.setCheckedItem(R.id.nav_music);


        mNavView.setNavigationItemSelectedListener(item -> {
            mDrawerLayout.closeDrawer(GravityCompat.START);
            if (item.getItemId() == R.id.nav_exit_login) {
                if (mLoginFLag) {
                    Toast.makeText(MyApp.getContext(), "退出登录", Toast.LENGTH_SHORT).show();
                    exitLogin();
                } else {
                    Toast.makeText(MyApp.getContext(), "还没有登录，退出不了呢", Toast.LENGTH_SHORT).show();
                }
            }


            return true;
        });
    }

    @Override
    public void initListener() {
        setCircleImagineListener();
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_main;
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.tool_bar, menu);

        return true;
    }


    /**
     * 抽屉列表或者toolbar选择菜单的情况
     *
     * @param item 子菜单
     * @return 返回布尔
     */
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {

        switch (item.getItemId()) {
            case android.R.id.home:
                mDrawerLayout.openDrawer(GravityCompat.START);
                break;
            case R.id.action_search:
                Toast.makeText(MyApp.getContext(), "点击了search", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(HomeActivity.this, SearchActivity.class);
                startActivityForResult(intent, TURN_TO_SEARCH);
                break;
            default:
                break;
        }

        return true;
    }


    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.icon_image) {
            if (!mLoginFLag) {
                Intent intent = new Intent(HomeActivity.this, LoginActivity.class);
                startActivityForResult(intent, HOME_TO_LOGIN_ACTIVITY_CODE);
            }
            if (mLoginFLag) {
                Toast.makeText(this, "别点击我小头像么", Toast.LENGTH_SHORT).show();
            }
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == HOME_TO_LOGIN_ACTIVITY_CODE) {
            if (resultCode == RESULT_OK) {
                assert data != null;
                String username = data.getStringExtra("username");
                loginChangeUi(username);
            }
        }
    }


    private void loginChangeUi(String username) {
        mLoginFLag = true;
        mTvUsername.setText(username);


    }

    /**
     * 动态申请权限
     *
     * @param permission 要申请的权限
     */
    private void requestPermission(String permission) {
        if (!(ActivityCompat.checkSelfPermission(this, permission) ==
                PackageManager.PERMISSION_GRANTED))
            ActivityCompat.requestPermissions(this, new String[]{permission}, 1024);
    }


    private void autoLogin() {
        mPreferences = getSharedPreferences("DATA", MODE_PRIVATE);
        String cookie = mPreferences.getString("cookie", "NOT_LOGIN");
        sJSessionId = cookie;
        System.out.println("饼干是" + cookie);
        if (!"NOT_LOGIN".equals(cookie)) {
            loginChangeUi(mPreferences.getString("username", ""));
        }
    }

    private void exitLogin() {
        mPreferences = getSharedPreferences("DATA", MODE_PRIVATE);
        SharedPreferences.Editor editor = mPreferences.edit();
        editor.putString("cookie", "NOT_LOGIN");
        editor.clear();
        editor.apply();
        mLoginFLag = false;
        mTvUsername.setText("请登录");
        sJSessionId = "";
    }

    private void playMusicAndTurn(int position) {

        Intent turnToPlayIntent = new Intent(HomeActivity.this, PlayActivity.class);
        turnToPlayIntent.putExtra("musicList", (Serializable) mMusicList);
        turnToPlayIntent.putExtra("position", position);
        startActivity(turnToPlayIntent);
    }


    private void addMenu(int pos, View view) {

        PopupMenu popup = new PopupMenu(HomeActivity.this, view);
        //获取菜单填充器
        MenuInflater inflater = popup.getMenuInflater();

        //填充菜单
        inflater.inflate(R.menu.menu_manage_play, popup.getMenu());
        //绑定菜单项的点击事件
        popup.setOnMenuItemClickListener(item -> {

            switch (item.getItemId()) {
                case R.id.item_delete:
                    mMusicList.remove(pos);
                    myAdapter.setList(mMusicList);
                    myAdapter.notifyDataSetChanged();
                    break;
                case R.id.item_play:
                    playMusicAndTurn(pos);
                    break;
                default:
                    break;
            }


            return false;
        });
        //显示(这一行代码不要忘记了)
        popup.show();
    }


}